import Vue from 'vue'
import App from './App.vue'
import router from './router'
import VueRouter from 'vue-router'
import store from './store'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import axios from 'axios'
import VueAxios from 'vue-axios'
import VueCookies from 'vue-cookies'
Vue.use(VueCookies)
let baseUrl = 'http://localhost:8090/'
Vue.prototype.$baseUrl=baseUrl
Vue.config.productionTip = false
Vue.use(ElementUI)
Vue.use(VueAxios, axios)
import * as echarts from 'echarts'
Vue.prototype.$echarts = echarts


//动态添加路由
router.beforeEach((to,from,next)=>{

  if(to.path=='/'){

    let indexChildrenRouters = [];
    axios.get(baseUrl+'menu/getTreeMenuByUsername').then(res=>{
      let menuData = res.data.data;
      menuData.forEach(menu=>{
        let subMenuList = menu.subMenuList;
        subMenuList.forEach(subMenu=>{
          let newRouter = {
            name: subMenu.name,
            path: subMenu.path
          }
          newRouter.component = () => import( './views/'+subMenu.component+'.vue');
          indexChildrenRouters.push(newRouter);
        })
      })
      router.options.routes[0].children = indexChildrenRouters;
      router.addRoutes(router.options.routes);
    })

  }
  next();
})



//请求拦截器和相应拦截器
// 添加请求拦截器

axios.interceptors.request.use(function (config) {
  // 在发送请求之前做些什么

  var token = $cookies.get("tokenId")

  if(token){
    //然后拼接到请求头  ctrl shift  r
    //如果localStorage中有token,就把token放入请求头
    config.headers.token = token
  }
  return config;
}, function (error) {
  // 对请求错误做些什么

  return Promise.reject(error);
});

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
  //console.log(response.data)
  console.log("====>"+response.data.msg)
  if(response.data.code==401 ||response.data.code==405){
    router.push("/login")
  }
  return response;
}, function (error) {
  // 对响应错误做点什么

  return Promise.reject(error);
});

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')
